package com.supervision.manage.service

import com.fly.base.exception.NotExistsException
import com.fly.base.misc.pagination.Pagination
import com.fly.base.util.DateFormatUtil
import com.fly.base.util.Util
import com.supervision.domain.bean.dc.CaseEnforceProcess
import com.supervision.domain.bean.dc.SdkApp
import com.supervision.domain.bean.po.CaseEnforcePO
import com.supervision.domain.bean.po.SmsPO
import com.supervision.domain.bean.vo.CaseEnforceVO
import com.supervision.domain.enums.CaseEnforceEnum
import com.supervision.manage.mapper.CaseEnforceMapper
import com.supervision.domain.model.CaseEnforce
import com.supervision.domain.model.User
import com.supervision.manage.mapper.SmsTemplateMapper
import org.apache.commons.lang3.StringUtils
import org.apache.commons.text.StringSubstitutor
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service("CaseEnforceService")
class CaseEnforceService {

    companion object {
        private val logger = org.slf4j.LoggerFactory.getLogger(CaseEnforceService::class.java)

        @JvmStatic
        fun main(args: Array<String>) {
            val statusArr = arrayListOf<String>()
            val statusIdList = Util.parseIdString("40,2,1")
            // 默认流程
            var defaultProcess = CaseEnforceProcess.statusProcessOne
            statusIdList.forEachIndexed { index, it ->
                val status = it.toInt()
                if (index == 0) {
                    statusArr.add(CaseEnforceEnum.getStatusTxt(status))
                    return@forEachIndexed
                } else if (index == 1 && status == 2) {
                    // 如果第一位为不成功
                    defaultProcess = CaseEnforceProcess.statusProcessTwo
                }

                val process = defaultProcess[index]!!

                process[status]?.let { it -> statusArr.add(it) }
            }

            println(StringUtils.join(statusArr, "-"))
        }
    }

    @Autowired
    lateinit var caseEnforceMapper: CaseEnforceMapper

    @Autowired
    lateinit var caseUserService: CaseUserService

    @Autowired
    lateinit var smsTemplateMapper: SmsTemplateMapper

    fun select(condition: CaseEnforce, otherCondition: String?): List<CaseEnforce> {
        return caseEnforceMapper.select(condition, otherCondition)
    }

    fun getCaseEnforceList(po: CaseEnforcePO): HashMap<String, Any> {
        val list: List<CaseEnforceVO> = caseEnforceMapper.getCaseEnforceList(po, Pagination.limitSql(po.page, po.pageSize))
        list.forEach { it ->
            it.caseUserList = caseUserService.getCaseUserList(it.id)
            it.statusTxt = CaseEnforceEnum.getStatusTxt(it.status)

            it.timeout = if ((DateFormatUtil.time() - it.createTime) > 86400 * 15) {
                1
            } else {
                0
            }
        }
        val count = caseEnforceMapper.countCaseEnforceList(po, "")

        return hashMapOf(
                "list" to list,
                "count" to count
        )
    }

    fun getCaseEnforceDetail(id: Long): HashMap<String, Any> {
        val vo: CaseEnforceVO = caseEnforceMapper.findById(id) ?: throw NotExistsException("案件不存在")

        vo.caseUserList = caseUserService.getCaseUserList(vo.id)
        val applyUser = User.findById(vo.applyUserId)
        vo.name = applyUser?.name ?: ""
        vo.nickname = applyUser?.nickname ?: ""
        vo.phone = applyUser?.phone ?: ""

        vo.statusProcessTxt = this.formatCaseEnforceStatusProcess(vo.statusProcess)

        return hashMapOf(
                "caseEnforce" to vo
        )
    }

    /**
     * 将
     */
    private fun formatCaseEnforceStatusProcess(statusProcess: String): String {
        if (statusProcess.isEmpty()) {
            return ""
        }

        val statusArr = arrayListOf<String>()
        val statusIdList = Util.parseIdString(statusProcess)
        // 默认流程
        var defaultProcess = CaseEnforceProcess.statusProcessOne
        statusIdList.forEachIndexed { index, it ->
            val status = it.toInt()
            if (index == 0) {
                statusArr.add(CaseEnforceEnum.getStatusTxt(status))
                return@forEachIndexed
            } else if (index == 1 && status == 2) {
                // 如果第一位为不成功
                defaultProcess = CaseEnforceProcess.statusProcessTwo
            }

            val process = defaultProcess[index] as HashMap<Int, String>

            process[status]?.let { it -> statusArr.add(it) }
        }

        return StringUtils.join(statusArr, "-")
    }

    fun caseEnforceRemark(id: Long, statusProcess: String, remark: String) {
        val caseEnforce = CaseEnforce.findOrFail(id)

        caseEnforce.statusProcess = statusProcess
        if (statusProcess.isNotEmpty()) {
            val idList = Util.parseIdString(statusProcess)
            if (idList.size > 0) {
                caseEnforce.status = idList[0].toInt()
            }
        }
        if (remark.isNotEmpty()) {
            caseEnforce.backRemark = remark
        }
        caseEnforce.save()
    }

    fun getSmsContent(caseId: Long, type: Int): HashMap<String, Any> {
        val po = SmsPO()
        po.type = type
        val smsTemplateList = smsTemplateMapper.getSmsTemplateList(po, Pagination.limitSql(1, 100))
        val caseEnforce = CaseEnforce.findOrFail(caseId)
        val smsApp = SdkApp.initSmsAppConfig()
        val param = hashMapOf<String, String>()
        param["sign"] = "【${smsApp.smsSign}】"
        param["sn"] = caseEnforce.sn
        smsTemplateList.forEach { it ->
            val templateParams = StringSubstitutor(param)
            it.templateContent = templateParams.replace(it.content)
        }

        return hashMapOf<String, Any>(
                "list" to smsTemplateList
        )
    }
}
